#include "Queue.h"

void QueueInit(Queue* pq)
{
    assert(pq);

    pq->phead = pq->ptail = NULL;
    pq->size = 0;
}

void QueueDestroy(Queue* pq)
{
    assert(pq);

    QNode* cur = pq->phead;
    while (cur)
    {
        QNode* tmp = cur->next;
        cur = cur->next;
        free(tmp);
        tmp = NULL;
    }
    pq->phead = pq->ptail = NULL;
    pq->size = 0;
}

void QueuePush(Queue* pq, QDataType x)
{
    assert(pq);

    QNode* newnode = (QNode*)malloc(sizeof(QNode));
    if (NULL == newnode)
    {
        perror("QueuePush malloc fail");
        return;
    }

    newnode->val = x;
    newnode->next = NULL;
    if (NULL == pq->phead)
    {
        pq->phead = pq->ptail = newnode;
    }
    else 
    {
        pq->ptail->next = newnode;
        pq->ptail = newnode;
    }
    ++pq->size;
}

void QueuePop(Queue* pq)
{
    assert(pq);
    assert(!QueueEmpty(pq));

    QNode* tmp = pq->phead;
    pq->phead = pq->phead->next;
    free(tmp);
    tmp = NULL;
    --pq->size;
}

QDataType QueueFront(Queue* pq)
{
    assert(pq);
    assert(!QueueEmpty(pq));

    return pq->phead->val;
}

QDataType QueueBack(Queue* pq)
{
    assert(pq);
    assert(!QueueEmpty(pq));

    return pq->ptail->val;
}

bool QueueEmpty(Queue* pq)
{
    assert(pq);

    return pq->size == 0;
}

int QueueSize(Queue* pq)
{
    assert(pq);

    return pq->size;
}